package org.linlinjava.litemall.wx.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import org.linlinjava.litemall.core.util.CharUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallRecharge;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.UserRechargeVo;
import org.linlinjava.litemall.db.service.LitemallRechargeService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.dto.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserInfoService {
    @Autowired
    private LitemallUserService userService;

    @Autowired
    private LitemallRechargeService rechargeService;

    public UserInfo getInfo(Integer userId) {
        LitemallUser user = userService.findById(userId);
        Assert.state(user != null, "用户不存在");
        UserInfo userInfo = new UserInfo();
        userInfo.setNickName(user.getNickname());
        userInfo.setAvatarUrl(user.getAvatar());
        return userInfo;
    }

    @Transactional(rollbackFor = Throwable.class)
    public Object recharge(Integer userId, UserRechargeVo userRechargeVo) {
        if (Objects.isNull(userId)) {
            return ResponseUtil.unlogin();
        }
        if (BigDecimal.ZERO.compareTo(userRechargeVo.getRechargeAmount()) > 0) {
            return ResponseUtil.badArgumentValue();
        }
        LitemallUser user = userService.findById(userId);
        String now = LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.PURE_DATETIME_PATTERN);
        String traceSn = now + CharUtil.getRandomNum(6);
        BigDecimal totalAmount = user.getRemainAmount().add(userRechargeVo.getRechargeAmount());

        LitemallRecharge recharge = new LitemallRecharge();
        recharge.setUserId(user.getId());
        recharge.setTraceSn(traceSn);
        recharge.setMobile(user.getMobile());
        recharge.setRechargeAmount(userRechargeVo.getRechargeAmount());
        recharge.setGiveAmount(userRechargeVo.getGiveAmount());
        recharge.setTotalAmount(totalAmount);
        recharge.setRechargeWay("用户充值");
        rechargeService.add(recharge);

        user.setRemainAmount(totalAmount);
        userService.updateById(user);
        Map<String, Object> result = new HashMap<>(1);
        result.put("remainAmount", user.getRemainAmount());
        return ResponseUtil.ok(result);
    }
}
